package com.sinoeyes.common.filter;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sinoeyes.common.core.page.RestPageResult;
import com.sinoeyes.common.utils.StringUtils;
import com.sinoeyes.common.utils.sql.SqlUtil;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author steven.zhang
 * @Description
 * @date 2019/10/10
 */
@ApiModel
@Data
public class BaseQueryFilter implements Serializable {

    private static final long serialVersionUID = 1L;

    /** 数据权限 */
    private String dataScope;

    /**
     * 当前记录起始索引
     */
    @ApiModelProperty("当前记录起始索引")
    private Integer pageNum = 1;
    /**
     * 每页显示记录数
     */
    @ApiModelProperty("每页显示记录数")
    private Integer pageSize = 10;
    /**
     * 排序列
     */
    @ApiModelProperty("排序列")
    private String orderByColumn;
    /**
     * 排序的方向 "desc" 或者 "asc".
     */
    @ApiModelProperty("排序的方向 \"desc\" 或者 \"asc\".")
    private String isAsc;

    /**
     * 请求参数
     */
    @JsonIgnore
    private Map<String, Object> params;

    public Map<String, Object> getParams() {
        if (params == null) {
            params = new HashMap<>();
        }
        return params;
    }

    public String getOrderBy() {
        if (StringUtils.isEmpty(orderByColumn)) {
            return "";
        }
        return StringUtils.toUnderScoreCase(orderByColumn) + " " + isAsc;
    }

    /**
     * 设置请求分页数据
     */
    public void startPage() {
        Integer pageNum = getPageNum();
        Integer pageSize = getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    public RestPageResult getPageResult(List<?> list) {
        RestPageResult pageResult = new RestPageResult();
        pageResult.setRows(list);
        pageResult.setTotal(new PageInfo(list).getTotal());
        return pageResult;
    }
}
